package com.driver.manage.ocr;

import com.alibaba.fastjson2.JSONObject;
import com.driver.manage.utils.*;
import okhttp3.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

/**
 * @author JiJunLing
 */
public class ImageRecognize {

    public static final String API_KEY = "cnrWf5fH4yzHc3gUYqixbSu2";
    public static final String SECRET_KEY = "95oPWkyMhf6TU3S8B0hD2atasgX3lAH9";

    public static String recognize(String requestUrl, File file) {
        // 请求url
        String url = requestUrl;
        try {
            byte[] imgData = FileUtil.readFileByBytes(String.valueOf(file));
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "id_card_side=" + "front" + "&image=" + imgParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.b8ed5eecb868ccb95a3be0eb81e4aefe.2592000.1690196267.282335-35245660";
            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * 获取文件base64编码
     *
     * @param
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(MultipartFile file, boolean urlEncode) throws IOException {
        byte[] data = null;
        String base64 = null;
        data = file.getBytes();
        base64 = Base64.getEncoder().encodeToString(data);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        Response response = null;
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        response = HTTP_CLIENT.newCall(request).execute();
        String access_token = JSONObject.parse(response.body().string()).get("access_token").toString();
        return access_token;
    }

    public static Object getBioAssayResult(MultipartFile file) throws IOException {
        Response response = null;
        try {
            String token = getAccessToken();
            Thread.sleep(1000);
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "video_base64=" + getFileContentAsBase64(file, true));
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rest/2.0/face/v1/faceliveness/verify?access_token=" + token)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            response = HTTP_CLIENT.newCall(request).execute();
            System.out.println();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return JSONObject.parse(response.body().string());
    }
}
